package com.yxr.affairs.utils;


import android.content.Context;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

public class Utils {

    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return  dp * scale + 0.5f;
    }

    public static float sp2px(Resources resources, float sp){
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    /**
     * RSA加密
     *
     * @param context
     * @param source
     * @return
     */
    public static String rsaEncode(Context context, String source) {
        String afterencrypt="";
        try {
            // 从字符串中得到公钥
            // PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
            // 从文件中得到公钥
            InputStream inPublic = context.getResources().getAssets().open("rsa_public_key.pem");
            String i = inPublic.toString();

            LogUtil.log(i);

            PublicKey publicKey = RsaUtils.loadPublicKey(inPublic);
            // 加密
            byte[] encryptByte = RsaUtils.encryptData(source.getBytes(), publicKey);
            // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
            afterencrypt = Base64Utils.encode(encryptByte);
        } catch (Exception e) {
            e.printStackTrace();
            return afterencrypt;
        }
        return afterencrypt;
    }

    /**
     * RSA解密
     *
     * @param context
     * @param source
     * @return
     */
    public static String rsaDecode(Context context,String source) {
        String decryptStr="";
        try {
            // 从字符串中得到私钥
            // PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
            // 从文件中得到私钥
            InputStream inPrivate = context.getResources().getAssets().open("pkcs8_rsa_private_key.pem");
            PrivateKey privateKey = RsaUtils.loadPrivateKey(inPrivate);
            // 因为RSA加密后的内容经Base64再加密转换了一下，所以先Base64解密回来再给RSA解密
            byte[] decryptByte = RsaUtils.decryptData(Base64Utils.decode(source), privateKey);
            decryptStr = new String(decryptByte);
        } catch (Exception e) {
            e.printStackTrace();
            return decryptStr;
        }
        return decryptStr;
    }

    /**
     * 判断是否有网络连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
}
